package enterprise.manage.security;

import enterprise.manage.dao.UserDao;
import enterprise.manage.entity.User;
import enterprise.manage.security.utils.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.*;
import org.springframework.security.context.HttpSessionContextIntegrationFilter;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
import org.springframework.security.ui.AuthenticationDetailsSource;
import org.springframework.security.ui.AuthenticationDetailsSourceImpl;
import org.springframework.security.ui.webapp.AuthenticationProcessingFilter;
import org.springframework.transaction.annotation.Transactional; 
import javax.servlet.http.HttpServletRequest;

/**
 * Created by IntelliJ IDEA.
 * User: zhenmingyue
 * Date: 2012-11-21 
 * desc
 */
@Transactional
public class LoginHandler {
    /**
     * 日志
     */
    private final Logger logger = LoggerFactory.getLogger(LoginHandler.class);
    /**
     * AuthenticationDetailsSource
     */
    protected final AuthenticationDetailsSource authenticationDetailsSource = new AuthenticationDetailsSourceImpl();
    /**
     * AuthenticationManager
     */
    private AuthenticationManager authenticationManager;
    /**
     * 用户dao
     */
    @Autowired
    private UserDao userDao ;

    /**
     * 登录方法
     *
     * @param username 用户名
     * @param password 密码
     * @param request  HttpServletRequest
     * @throws org.springframework.security.AuthenticationException AuthenticationException
     */
    public void login(String username, String password, HttpServletRequest request) throws AuthenticationException {
        if (logger.isDebugEnabled()) {
            logger.info("用户登录（用户名" + username + "）");
        }
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username
                , password);
        request.getSession().setAttribute(AuthenticationProcessingFilter.SPRING_SECURITY_LAST_USERNAME_KEY, username);
        try {
            authenticationToken = (UsernamePasswordAuthenticationToken)
                    authenticationManager.authenticate(authenticationToken);
            authenticationToken.setDetails(authenticationDetailsSource.buildDetails(request));
        } catch (AuthenticationException authenticationException) {
            if (authenticationException instanceof AuthenticationCredentialsNotFoundException) {
                logger.warn("登录异常：用户名(" + username + ")不存在，请重新输入");
            } else if (authenticationException instanceof BadCredentialsException) {
                logger.warn("登录异常：用户名(" + username + ")的密码错误，请重新输入");
            } else if (authenticationException instanceof DisabledException) {
                logger.warn("登录异常：用户名(" + username + ")没有激活");
            } else {
                logger.warn("登录异常：用户名被锁定");
            }

            throw authenticationException;
        }

        logger.info("登录成功(" + username + ")...");

        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        request.getSession().setAttribute(HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY
                , SecurityContextHolder.getContext());

        User User = userDao.findByUnique("userName",username);
        request.getSession().setAttribute(SecurityUtils.SESSION_USER_ID, User.getId());
    }

    public void setAuthenticationManager(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
}

